package hibari.client.ui;

import hibari.client.model.ClientServices;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class WeekBrowser extends Composite implements ClickHandler, AsyncCallback<List<Integer>> {

	interface WeekBorwserUiBinder extends UiBinder<Widget, WeekBrowser> {
	}

	private static WeekBorwserUiBinder uiBinder = GWT.create(WeekBorwserUiBinder.class);

	@UiField
	protected FlexTable grid;

	private Cell selectedCell;

	private SelectionHandler<Integer> selectionHandler;

	private List<Integer> weeks;

	public WeekBrowser() {
		initWidget(uiBinder.createAndBindUi(this));
		this.grid.addClickHandler(this);
	}

	public void loadAndShowContents() {
		ClientServices.weekService.getAllWeekNumbers(this);
	}

	public SelectionHandler<Integer> getSelectionHandler() {
		return this.selectionHandler;
	}

	@Override
	public void onClick(ClickEvent event) {
		Cell cell = this.grid.getCellForEvent(event);
		if (this.selectedCell == cell) {
			return;
		}

		if (this.selectedCell != null) {
			this.grid.getFlexCellFormatter().removeStyleName(this.selectedCell.getRowIndex(),
					this.selectedCell.getCellIndex(), "selection");
		}

		this.selectedCell = cell;
		if (this.selectedCell != null) {
			this.grid.getFlexCellFormatter().addStyleName(this.selectedCell.getRowIndex(),
					this.selectedCell.getCellIndex(), "selection");
			this.selectedCell.getElement().scrollIntoView();
		}

		if (this.selectionHandler != null) {
			this.selectionHandler.selectionChanged(this.weeks.get(this.selectedCell.getRowIndex()));
		}

	}

	@Override
	public void onFailure(Throwable caught) {
		caught.printStackTrace();
	}

	@Override
	public void onSuccess(List<Integer> result) {
		this.weeks = result;
		for (int i = 0; i < result.size(); i++) {
			this.grid.setWidget(i, 0, new Label("Week #" + result.get(i)));
		}
	}

	public void setSelectionHandler(SelectionHandler<Integer> selectionHandler) {
		this.selectionHandler = selectionHandler;
	}

}
